package cn.aitrox.ry.service.anno.config;

import cn.aitrox.ry.service.anno.mq.consumer.FileHandlerConsumer;
import cn.aitrox.ry.service.anno.mq.consumer.Mask2niiConsumer;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.DefaultMessageListenerContainer;

import javax.jms.Queue;

@Configuration
public class ActivemqConfig {

    public static final String MASK_2_NII_QUEUE = "MASK_2_NII_QUEUE";
    public static final String FILE_HANDLER_QUEUE = "FILE_HANDLER_QUEUE";

    @Value("${spring.activemq.user}")
    private String usrName;

    @Value("${spring.activemq.password}")
    private String password;

    @Value("${spring.activemq.brokerUrl}")
    private String brokerUrl;

    @Bean("fileHandlerQueue")
    public Queue fileHandlerQueue() {
        return new ActiveMQQueue(FILE_HANDLER_QUEUE);
    }


    @Bean("mask2niiQueue")
    public Queue mask2niiQueue() {
        return new ActiveMQQueue(MASK_2_NII_QUEUE);
    }


    @Bean
    public ActiveMQConnectionFactory amqConnectionFactory() {
        return new ActiveMQConnectionFactory(usrName, password, brokerUrl);
    }

    //
    @Bean
    public JmsTemplate jmsTemplate(ActiveMQConnectionFactory amqConnectionFactory) {
        // 默认队列模式
        JmsTemplate jmsTemplate = new JmsTemplate(amqConnectionFactory);
        jmsTemplate.setConnectionFactory(amqConnectionFactory);
        return jmsTemplate;
    }

    @Bean
    public DefaultMessageListenerContainer fileHandlerContainer(ActiveMQConnectionFactory activeMQConnectionFactory, Queue fileHandlerQueue, FileHandlerConsumer msglistener) {
        DefaultMessageListenerContainer container = genCommonContainer(activeMQConnectionFactory, fileHandlerQueue);
        container.setMessageListener(msglistener);
        container.setConcurrentConsumers(5);
        return container;
    }


    @Bean
    public DefaultMessageListenerContainer mask2niiContainer(ActiveMQConnectionFactory activeMQConnectionFactory, Queue mask2niiQueue, Mask2niiConsumer msglistener) {
        DefaultMessageListenerContainer container = genCommonContainer(activeMQConnectionFactory, mask2niiQueue);
        container.setMessageListener(msglistener);
        return container;
    }

    private DefaultMessageListenerContainer genCommonContainer(ActiveMQConnectionFactory factory, Queue queue) {
        DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();
        container.setConnectionFactory(factory);
        container.setDestination(queue);
        return container;
    }


}
